package cn.stylefeng.guns.modular.filerun.service;

import cn.stylefeng.guns.config.OssConfig;
import cn.stylefeng.guns.modular.filerun.mapper.FileImgMapper;
import cn.stylefeng.guns.modular.filerun.model.FileUploadResult;
import cn.stylefeng.guns.modular.filerun.uploadclient.OssToolsClient;
import cn.stylefeng.guns.sys.modular.system.entity.FileImgPO;
import com.aliyun.oss.model.DeleteObjectsRequest;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;
import org.springframework.web.multipart.MultipartFile;

import java.util.ArrayList;
import java.util.List;

@Service
@Slf4j
public class FileImgService extends ServiceImpl<FileImgMapper, FileImgPO> {

    @Autowired
    private OssToolsClient ossToolsClient;
    @Autowired
    private OssConfig ossConfig;

    //上传图片
    public FileUploadResult uploadFileByOss(MultipartFile file) {
        try {
            return ossToolsClient.uploadByOss(file);
        } catch (Exception e) {
            e.getStackTrace();
        }
        return null;
    }
    //批量删除图片
    public FileUploadResult removeFileByOss(List<String> imgUrls) {
        try {
            FileUploadResult fileUploadResult = ossToolsClient.deleteBatch(processData(imgUrls));
            return fileUploadResult;
        } catch (Exception e) {
            e.getStackTrace();
        }
        return null;
    }

    private List<String> processData(List<String> imgUrls){
        if(CollectionUtils.isEmpty(imgUrls)){
            return null;
        }
        List<String> results = new ArrayList<>(imgUrls.size());
        imgUrls.forEach(s -> {
            results.add(s.split(ossConfig.getWebUrl())[1]);
        });
        return results;
    }

}
